// 生日祝福页面脚本

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 创建彩色纸屑效果
    createConfetti();
    
    // 初始化照片轮播
    initPhotoCarousel();
    
    // 初始化音乐控制并尝试立即播放
    initMusicControl();
    
    // 如果存在倒计时元素，启动倒计时
    if(document.getElementById('countdown')) {
        startCountdown();
    }
    
    // 如果存在打字效果元素，启动打字效果
    if(document.getElementById('typing-text')) {
        typeWriter();
    }
    
    // 添加爱心点击效果
    document.addEventListener('click', function(event) {
        createHeartEffect(event);
        createTapEffect(event);
        
        // 点击页面任何地方也尝试播放音乐
        tryPlayMusic();
    });
    
    // 添加互动元素事件
    initInteractiveElements();
    
    // 如果有祝福按钮，添加点击事件
    const wishButton = document.getElementById('wish-button');
    if(wishButton) {
        wishButton.addEventListener('click', showBirthdayMessage);
    }
});

// 尝试播放音乐的函数，多处调用增加自动播放成功率
function tryPlayMusic() {
    const audio = document.getElementById('birthdaySong');
    const musicToggle = document.getElementById('musicToggle');
    
    if(audio && audio.paused) {
        const playPromise = audio.play();
        
        if(playPromise !== undefined) {
            playPromise.then(() => {
                // 播放成功
                musicToggle.classList.add('playing');
            }).catch(error => {
                // 自动播放失败，正常情况，不做处理
                console.log('尝试播放失败，将在用户交互时再次尝试');
            });
        }
    }
}

// 创建彩色纸屑效果
function createConfetti() {
    const colors = ['#ff1493', '#ff69b4', '#ffb6c1', '#ffc0cb', '#ffd700', '#ff8c00', '#ff4500'];
    const confettiCount = 100;
    
    for (let i = 0; i < confettiCount; i++) {
        const confetti = document.createElement('div');
        confetti.className = 'confetti';
        confetti.style.left = Math.random() * 100 + 'vw';
        confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        confetti.style.width = Math.random() * 10 + 5 + 'px';
        confetti.style.height = Math.random() * 10 + 5 + 'px';
        confetti.style.animationDuration = Math.random() * 3 + 3 + 's';
        confetti.style.animationDelay = Math.random() * 5 + 's';
        document.body.appendChild(confetti);
    }
    
    // 定期清理纸屑，避免DOM元素过多
    setInterval(() => {
        const confettis = document.querySelectorAll('.confetti');
        if(confettis.length > 300) {
            for(let i = 0; i < 100; i++) {
                if(confettis[i]) confettis[i].remove();
            }
        }
    }, 10000);
}

// 初始化照片轮播
function initPhotoCarousel() {
    const carouselItems = document.querySelectorAll('.carousel-item');
    const carouselDots = document.querySelectorAll('.carousel-dot');
    let currentIndex = 0;
    let interval;
    
    // 显示当前照片
    function showPhoto(index) {
        // 隐藏所有照片
        carouselItems.forEach(item => {
            item.classList.remove('active');
        });
        
        // 移除所有导航点的激活状态
        carouselDots.forEach(dot => {
            dot.classList.remove('active');
        });
        
        // 显示当前照片
        carouselItems[index].classList.add('active');
        carouselDots[index].classList.add('active');
        
        currentIndex = index;
    }
    
    // 显示下一张照片
    function nextPhoto() {
        let nextIndex = (currentIndex + 1) % carouselItems.length;
        showPhoto(nextIndex);
    }
    
    // 初始显示第一张照片
    showPhoto(0);
    
    // 设置自动轮播
    interval = setInterval(nextPhoto, 4000);
    
    // 为导航点添加点击事件
    carouselDots.forEach((dot, index) => {
        dot.addEventListener('click', () => {
            clearInterval(interval);
            showPhoto(index);
            interval = setInterval(nextPhoto, 4000);
        });
    });
    
    // 触摸滑动支持（手机端）
    const carousel = document.querySelector('.photo-carousel');
    let startX, endX;
    
    carousel.addEventListener('touchstart', (e) => {
        startX = e.touches[0].clientX;
        clearInterval(interval);
    }, { passive: true });
    
    carousel.addEventListener('touchmove', (e) => {
        endX = e.touches[0].clientX;
    }, { passive: true });
    
    carousel.addEventListener('touchend', () => {
        const threshold = 50; // 滑动阈值
        if (startX - endX > threshold) {
            // 向左滑动，显示下一张
            let nextIndex = (currentIndex + 1) % carouselItems.length;
            showPhoto(nextIndex);
        } else if (endX - startX > threshold) {
            // 向右滑动，显示上一张
            let prevIndex = (currentIndex - 1 + carouselItems.length) % carouselItems.length;
            showPhoto(prevIndex);
        }
        
        interval = setInterval(nextPhoto, 4000);
    }, { passive: true });
}

// 初始化音乐控制
function initMusicControl() {
    const musicToggle = document.getElementById('musicToggle');
    const audio = document.getElementById('birthdaySong');
    
    // 设置音频为预加载
    audio.preload = "auto";
    
    // 尝试多种方式触发自动播放
    // 方法1: 直接尝试播放
    tryPlayMusic();
    
    // 方法2: 延迟尝试播放
    setTimeout(tryPlayMusic, 500);
    setTimeout(tryPlayMusic, 1500);
    setTimeout(tryPlayMusic, 3000);
    
    // 方法3: 添加用户交互事件监听
    document.addEventListener('touchstart', function() {
        tryPlayMusic();
    }, { once: true, passive: true });
    
    // 方法4: 页面滚动时尝试播放
    window.addEventListener('scroll', function() {
        tryPlayMusic();
    }, { once: true, passive: true });
    
    // 点击图标切换音乐播放状态
    musicToggle.addEventListener('click', () => {
        if (audio.paused) {
            audio.play();
            musicToggle.classList.add('playing');
        } else {
            audio.pause();
            musicToggle.classList.remove('playing');
        }
    });
    
    // 页面可见性变化时控制音乐
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            // 页面不可见时不暂停音乐，让音乐继续播放
            // audio.pause();
            // musicToggle.classList.remove('playing');
        } else if (!audio.paused) {
            audio.play();
            musicToggle.classList.add('playing');
        }
    });
    
    // 监听音频播放状态
    audio.addEventListener('play', () => {
        musicToggle.classList.add('playing');
    });
    
    audio.addEventListener('pause', () => {
        musicToggle.classList.remove('playing');
    });
}

// 创建点击爱心效果
function createHeartEffect(event) {
    const heart = document.createElement('div');
    heart.innerHTML = '❤️';
    heart.className = 'click-heart';
    heart.style.position = 'absolute';
    heart.style.left = (event.clientX - 10) + 'px';
    heart.style.top = (event.clientY - 10) + 'px';
    heart.style.fontSize = '20px';
    heart.style.pointerEvents = 'none';
    heart.style.userSelect = 'none';
    heart.style.animation = 'float 2s ease-out forwards';
    heart.style.opacity = '1';
    heart.style.zIndex = '9999';
    
    document.body.appendChild(heart);
    
    // 2秒后移除爱心元素
    setTimeout(() => {
        heart.remove();
    }, 2000);
}

// 创建点击波纹效果
function createTapEffect(event) {
    const tapEffect = document.createElement('div');
    tapEffect.className = 'tap-effect';
    tapEffect.style.left = event.clientX + 'px';
    tapEffect.style.top = event.clientY + 'px';
    
    document.body.appendChild(tapEffect);
    
    // 动画结束后移除元素
    setTimeout(() => {
        tapEffect.remove();
    }, 500);
}

// 初始化互动元素
function initInteractiveElements() {
    const interactiveElements = document.querySelectorAll('.interactive-element');
    
    interactiveElements.forEach(element => {
        element.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止冒泡，避免触发文档的点击事件
            
            // 根据不同的元素显示不同的效果
            const emoji = element.textContent;
            
            if (emoji === '💕') {
                showFloatingHearts(e.clientX, e.clientY);
            } else if (emoji === '🌹') {
                showFloatingRoses(e.clientX, e.clientY);
            } else if (emoji === '🎁') {
                showGiftMessage();
            } else if (emoji === '✨') {
                createSparkles(e.clientX, e.clientY);
            }
            
            // 尝试播放音乐
            tryPlayMusic();
        });
    });
}

// 显示漂浮爱心
function showFloatingHearts(x, y) {
    for (let i = 0; i < 10; i++) {
        const heart = document.createElement('div');
        heart.innerHTML = '💕';
        heart.style.position = 'absolute';
        heart.style.left = (x - 10 + Math.random() * 20) + 'px';
        heart.style.top = (y - 10) + 'px';
        heart.style.fontSize = (15 + Math.random() * 15) + 'px';
        heart.style.pointerEvents = 'none';
        heart.style.opacity = '1';
        heart.style.zIndex = '9999';
        heart.style.transition = 'all 2s ease-out';
        heart.style.transform = 'translateY(0)';
        
        document.body.appendChild(heart);
        
        // 设置动画
        setTimeout(() => {
            heart.style.opacity = '0';
            heart.style.transform = `translateY(-${100 + Math.random() * 100}px)`;
        }, 10);
        
        // 移除元素
        setTimeout(() => {
            heart.remove();
        }, 2000);
    }
}

// 显示漂浮玫瑰
function showFloatingRoses(x, y) {
    for (let i = 0; i < 5; i++) {
        const rose = document.createElement('div');
        rose.innerHTML = '🌹';
        rose.style.position = 'absolute';
        rose.style.left = (x - 10 + Math.random() * 40 - 20) + 'px';
        rose.style.top = (y - 10) + 'px';
        rose.style.fontSize = (15 + Math.random() * 10) + 'px';
        rose.style.pointerEvents = 'none';
        rose.style.opacity = '1';
        rose.style.zIndex = '9999';
        rose.style.transition = 'all 2s ease-out';
        rose.style.transform = 'translateY(0) rotate(0deg)';
        
        document.body.appendChild(rose);
        
        // 设置动画
        setTimeout(() => {
            rose.style.opacity = '0';
            rose.style.transform = `translateY(-${50 + Math.random() * 100}px) rotate(${Math.random() * 360}deg)`;
        }, 10);
        
        // 移除元素
        setTimeout(() => {
            rose.remove();
        }, 2000);
    }
}

// 显示礼物消息
function showGiftMessage() {
    const messages = [
        '送你一个大大的拥抱！',
        '愿你每天都开心快乐！',
        '你是我最珍贵的礼物！',
        '爱你的每一天！',
        '永远支持你！'
    ];
    
    const randomMessage = messages[Math.floor(Math.random() * messages.length)];
    
    const messageBox = document.createElement('div');
    messageBox.textContent = randomMessage;
    messageBox.style.position = 'fixed';
    messageBox.style.top = '50%';
    messageBox.style.left = '50%';
    messageBox.style.transform = 'translate(-50%, -50%)';
    messageBox.style.backgroundColor = 'rgba(255, 105, 180, 0.9)';
    messageBox.style.color = 'white';
    messageBox.style.padding = '15px 20px';
    messageBox.style.borderRadius = '10px';
    messageBox.style.boxShadow = '0 5px 15px rgba(0,0,0,0.2)';
    messageBox.style.zIndex = '1000';
    messageBox.style.fontSize = '1.2rem';
    messageBox.style.textAlign = 'center';
    messageBox.style.animation = 'fadeIn 0.5s ease-out';
    
    document.body.appendChild(messageBox);
    
    // 3秒后移除消息
    setTimeout(() => {
        messageBox.style.animation = 'fadeOut 0.5s ease-in forwards';
        setTimeout(() => {
            messageBox.remove();
        }, 500);
    }, 3000);
}

// 创建闪光效果
function createSparkles(x, y) {
    const colors = ['#ff1493', '#ff69b4', '#ffd700', '#ff8c00', '#00bfff'];
    
    for (let i = 0; i < 20; i++) {
        const sparkle = document.createElement('div');
        sparkle.style.position = 'absolute';
        sparkle.style.width = (3 + Math.random() * 5) + 'px';
        sparkle.style.height = (3 + Math.random() * 5) + 'px';
        sparkle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        sparkle.style.borderRadius = '50%';
        sparkle.style.left = (x) + 'px';
        sparkle.style.top = (y) + 'px';
        sparkle.style.pointerEvents = 'none';
        sparkle.style.zIndex = '9999';
        sparkle.style.opacity = '1';
        sparkle.style.transition = 'all 1s ease-out';
        
        document.body.appendChild(sparkle);
        
        // 设置动画
        const angle = Math.random() * Math.PI * 2;
        const distance = 50 + Math.random() * 100;
        
        setTimeout(() => {
            sparkle.style.transform = `translate(${Math.cos(angle) * distance}px, ${Math.sin(angle) * distance}px)`;
            sparkle.style.opacity = '0';
        }, 10);
        
        // 移除元素
        setTimeout(() => {
            sparkle.remove();
        }, 1000);
    }
}

// 打字机效果
function typeWriter() {
    const element = document.getElementById('typing-text');
    const text = element.getAttribute('data-text');
    const speed = parseInt(element.getAttribute('data-speed')) || 100;
    
    if(!element.textContent) {
        let i = 0;
        function type() {
            if (i < text.length) {
                element.textContent += text.charAt(i);
                i++;
                setTimeout(type, speed);
            }
        }
        type();
    }
}

// 倒计时功能
function startCountdown() {
    const countdownElement = document.getElementById('countdown');
    const targetDate = new Date(countdownElement.getAttribute('data-target-date'));
    
    function updateCountdown() {
        const currentDate = new Date();
        const difference = targetDate - currentDate;
        
        if(difference <= 0) {
            countdownElement.innerHTML = "生日快乐！🎉";
            return;
        }
        
        const days = Math.floor(difference / (1000 * 60 * 60 * 24));
        const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((difference % (1000 * 60)) / 1000);
        
        countdownElement.innerHTML = `
            距离生日还有：
            <span>${days}</span>天
            <span>${hours}</span>时
            <span>${minutes}</span>分
            <span>${seconds}</span>秒
        `;
    }
    
    // 立即更新一次
    updateCountdown();
    
    // 每秒更新一次
    setInterval(updateCountdown, 1000);
}

// 显示生日祝福弹窗
function showBirthdayMessage() {
    const modal = document.createElement('div');
    modal.className = 'birthday-modal';
    modal.innerHTML = `
        <div class="birthday-modal-content">
            <span class="close-modal">&times;</span>
            <h2>亲爱的宝宝：</h2>
            <p>在你的特别日子里，我想对你说...</p>
            <p>生日快乐！愿你的每一天都像今天一样特别！</p>
            <p>永远爱你！❤️</p>
            <div class="modal-hearts"></div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // 添加关闭按钮功能
    const closeBtn = modal.querySelector('.close-modal');
    closeBtn.addEventListener('click', function() {
        modal.remove();
    });
    
    // 点击模态框外部也可以关闭
    window.addEventListener('click', function(event) {
        if (event.target === modal) {
            modal.remove();
        }
    });
    
    // 添加心形装饰
    const heartsContainer = modal.querySelector('.modal-hearts');
    for (let i = 0; i < 10; i++) {
        const heart = document.createElement('div');
        heart.className = 'modal-heart';
        heart.innerHTML = '❤️';
        heart.style.left = Math.random() * 100 + '%';
        heart.style.top = Math.random() * 100 + '%';
        heart.style.animationDelay = Math.random() * 3 + 's';
        heartsContainer.appendChild(heart);
    }
    
    // 弹窗显示时也尝试播放音乐
    tryPlayMusic();
} 